package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.AdNewsDto;
import com.heima.model.wemedia.dtos.AdScanDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AdNewsService;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements AdNewsService {

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    /**
     * 平台端查看文章列表数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult adminList(AdNewsDto dto) {

        // 校验参数
        dto.checkParam();

        // 分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dto.getTitle()), WmNews::getTitle, dto.getTitle())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .orderByDesc(WmNews::getCreatedTime);

        this.page(page,queryWrapper);

        List<WmNews> list = page.getRecords();

        if (Collections.isEmpty(list)) {
            PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
            pageResponseResult.setData(null);
            return pageResponseResult;
        }

        // 抽取用户id
        List<Integer> userIds = list.stream()
                .map(WmNews::getUserId)
                .collect(Collectors.toList());

        userIds = userIds.stream().distinct().collect(Collectors.toList());

        // 查询出所有的用户
        Map<Integer, String> userMap = wmUserMapper.selectBatchIds(userIds).stream().collect(Collectors.toMap(WmUser::getId, WmUser::getName));

        List<WmNewsVo> vos = new ArrayList<>();

        for (WmNews wmNews : list) {
            WmNewsVo vo = new WmNewsVo();
            BeanUtils.copyProperties(wmNews, vo);
            vo.setAuthorName(userMap.get(wmNews.getUserId()));

            vos.add(vo);
        }

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(vos);

        return pageResponseResult;
    }

    /**
     * 查看文章列表
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findById(Integer id) {
        // 校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 根据id查询数据
        WmNews wmnews = this.getById(id);
        if (wmnews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在!");
        }

        // 根据用户id查询，用户数据
        WmUser wmUser = wmUserMapper.selectById(wmnews.getUserId());

        // 封装数据
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmnews, vo);
        vo.setAuthorName(wmUser.getName());

        return ResponseResult.okResult(vo);
    }

    /**
     * 人工审核成功
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(AdScanDto dto) {

        // 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 根据id查询数据
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在!");
        }

        // 远程调用app端接口同步数据
        // 保存app端文章数据
        ResponseResult result = autoArticle(wmNews);
        if (!result.getCode().equals(200)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"审核失败");
        }

        // 修改状态和article_id
        wmNews.setStatus((short) 9);
        wmNews.setReason("文章发布成功");
        wmNews.setArticleId((Long) result.getData());
        this.updateById(wmNews);

        return ResponseResult.okResult("操作成功");
    }

    private ResponseResult autoArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        // 作者id和作者名称
        dto.setAuthorId(wmNews.getUserId().longValue());
        // 根据作者id查询作者名称
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null && wmUser.getName() != null) {
            dto.setAuthorName(wmUser.getName());
        }

        // 频道名称
        // 根据频道id，查询频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null && wmChannel.getName() != null) {
            dto.setChannelName(wmChannel.getName());
        }

        // 文章布局
        dto.setLayout(wmNews.getType());

        dto.setCreatedTime(new Date());

        ResponseResult result = articleClient.saveArticle(dto);

        return result;
    }

    /**
     * 人工审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AdScanDto dto) {

        // 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 根据id查询数据
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在!");
        }

        // 修改状态和错误信息
        wmNews.setStatus(dto.getStatus());
        wmNews.setReason(dto.getTitle());

        this.updateById(wmNews);

        return ResponseResult.okResult("操作成功");
    }

}
